package edu.ccut.saturn.studio.dialog.attributevalueassignmentdialog;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.search.SaturnFileSearcher.SearchResult;
import edu.ccut.saturn.studio.core.search.dialog.OneCompontentSearchDialog;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnSWTUtils;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnValidation;
import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.dialog.SelectionCandidate;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnDbDataElement;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnParameter;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnPropertyNode;
import edu.ccut.saturn.studio.util.ConversionUtil;

public class AttributeValueAssignmentDialog extends TitleAreaDialog {

	private Text idText;
	private TableViewer tableViewer;

	private Table table;

	private Text nameText, keyText, paraValueKeyText, fullKeyText,
			descriptionText;

	private SaturnPropertyNode saturnPropertyNode;

	private List<SaturnDbDataElement> dbDatalist;

	public AttributeValueAssignmentDialog(Shell parentShell,
			SaturnPropertyNode saturnPropertyNode) {
		super(parentShell);
		this.saturnPropertyNode = saturnPropertyNode;
	}

	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setMessage(Messages
				.getString("AttributeValueAssignmentDialog.AttributeValueComponent")); //$NON-NLS-1$
		return contents;
	}

	@Override
	protected Control createDialogArea(Composite parent) {

		getShell().setText(SelectionCandidate.ATTRIBUTE_SETTING);
		setTitleImage(Activator.getImage(Images.SATURN_ICONS_MAXNAME));

		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NONE);

		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 3;
		container.setLayout(gridLayout);
		final GridData gd_container = new GridData(SWT.FILL, SWT.FILL, true,
				true);
		container.setLayoutData(gd_container);

		final Label idLabel = new Label(container, SWT.NONE);
		final GridData gd_idLabel = new GridData();
		gd_idLabel.verticalIndent = 10;
		idLabel.setText(Messages.getString("AttributeValueAssignmentDialog.ID")); //$NON-NLS-1$

		idText = new Text(container, SWT.READ_ONLY | SWT.BORDER);
		
		final GridData gd_idText = new GridData(SWT.FILL, SWT.FILL, true, false,2,1);
		idText.setLayoutData(gd_idText);
		gd_idText.verticalIndent = 10;

		final Label nameLabel = new Label(container, SWT.NONE);
		final GridData gd_nameLabel = new GridData();
		gd_nameLabel.verticalIndent = 10;
		nameLabel.setLayoutData(gd_nameLabel);
		nameLabel.setText(Messages
				.getString("AttributeValueAssignmentDialog.name")); //$NON-NLS-1$

		nameText = new Text(container, SWT.BORDER);
		nameText.setTextLimit(50);

		final GridData gd_nameText = new GridData(SWT.FILL, SWT.FILL, true,
				false, 2, 1);
		gd_nameText.verticalIndent = 10;
		nameText.setLayoutData(gd_nameText);

		final Label keyValueLabel = new Label(container, SWT.NONE);
		final GridData gd_keyValueLabel = new GridData();
		gd_keyValueLabel.verticalIndent = 10;
		keyValueLabel.setLayoutData(gd_keyValueLabel);
		keyValueLabel.setText(Messages
				.getString("AttributeValueAssignmentDialog.expression")); //$NON-NLS-1$

		keyText = new Text(container, SWT.BORDER | SWT.READ_ONLY);
		final GridData gd_keyLabelText = new GridData(SWT.FILL, SWT.FILL, true,
				false, 2, 1);
		gd_keyLabelText.verticalIndent = 5;
		keyText.setLayoutData(gd_keyLabelText);

		final Label paraKVLabel = new Label(container, SWT.NONE);
		final GridData gd_paraKVLabel = new GridData();
		gd_paraKVLabel.verticalIndent = 10;
		paraKVLabel.setLayoutData(gd_paraKVLabel);
		paraKVLabel.setText(Messages
				.getString("AttributeValueAssignmentDialog.ParameterKeyValue")); //$NON-NLS-1$

		paraValueKeyText = new Text(container, SWT.BORDER);
		paraValueKeyText.setTextLimit(100);
		final GridData gd_paraKVText = new GridData(SWT.FILL, SWT.FILL, true,
				false, 2, 1);
		gd_paraKVText.verticalIndent = 5;
		paraValueKeyText.setLayoutData(gd_paraKVText);

		final Label fullKeyLabel = new Label(container, SWT.NONE);
		final GridData gd_fullKeyLabel = new GridData();
		gd_fullKeyLabel.verticalIndent = 10;
		fullKeyLabel.setLayoutData(gd_fullKeyLabel);
		fullKeyLabel.setText("FullKey:"); //$NON-NLS-1$

		fullKeyText = new Text(container, SWT.BORDER | SWT.READ_ONLY);
		final GridData gd_fullKeyText = new GridData(SWT.FILL, SWT.FILL, true,
				false);
		gd_fullKeyText.verticalIndent = 5;
		fullKeyText.setLayoutData(gd_fullKeyText);

		final Label imageLabel = new Label(container, SWT.NONE);
		imageLabel.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
		imageLabel.addMouseTrackListener(new MouseTrackAdapter() {
			public void mouseEnter(final MouseEvent mouseevent) {
				imageLabel.setImage(Activator.getImage(Images.AMPLIFY_MINUS));
			}

			public void mouseExit(final MouseEvent mouseevent) {
				imageLabel.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
			}
		});
		final GridData gd_imageLabel = new GridData();
		gd_imageLabel.verticalIndent = 6;
		imageLabel.setLayoutData(gd_imageLabel);

		imageLabel.addMouseListener(new MouseAdapter() {
			@SuppressWarnings("unchecked") //$NON-NLS-1$
			public void mouseDown(final MouseEvent e) {

				// FilterDialogForAttributeValueAssignmentNode dialog1 = new
				// FilterDialogForAttributeValueAssignmentNode(
				// Display.getDefault().getShells()[0], saturnPropertyNode);
				//
				// dialog1.setTitle(Messages.getString("AttributeValueAssignmentDialog.ChooseFullKey"));
				// //$NON-NLS-1$
				//
				// dialog1.setElements(ConversionUtil.conversion(saturnPropertyNode
				// .getMapfromProject().keySet()));
				//
				// if (dialog1.open() == Window.OK) {
				// fullKeyText.setText((String) dialog1.getFirstResult());
				//
				// if ((saturnPropertyNode.getProjectMap() != null)
				// && saturnPropertyNode.getProjectMap().containsKey(
				// fullKeyText.getText())) {
				// dbDatalist = xmlChange((List<SaturnDbDataElement>)
				// saturnPropertyNode
				// .getProjectMap().get(fullKeyText.getText()));
				//
				// } else if (saturnPropertyNode.getWorkspaceMap() != null
				// && saturnPropertyNode.getWorkspaceMap().containsKey(
				// fullKeyText.getText())) {
				// dbDatalist = xmlChange((List<SaturnDbDataElement>)
				// saturnPropertyNode
				// .getWorkspaceMap().get(fullKeyText.getText()));//
				// 得到一个list赋给第币李斯特
				// }
				// tableViewer.setInput(dbDatalist);
				// }
				OneCompontentSearchDialog searchDialog = new OneCompontentSearchDialog(
						Display.getDefault().getShells()[0], saturnPropertyNode);

				searchDialog
						.setTitle(Messages
								.getString("AttributeValueAssignmentDialog.ChooseFullKey")); //$NON-NLS-1$

				if (searchDialog.open() == Window.OK) {
					SearchResult fullyKey = (SearchResult) searchDialog
							.getFirstResult();
					fullKeyText.setText(fullyKey.getKey());
				
					
					Document document = fullyKey.getDocument();
					Node dataNode = SaturnW3CUtil.getFirstChildByName(document.getDocumentElement(), Messages.getString("AttributeValueAssignmentDialog.Data")); //$NON-NLS-1$
					Node fieldsNode = SaturnW3CUtil.getFirstChildByName(dataNode, Messages.getString("AttributeValueAssignmentDialog.Fields")); //$NON-NLS-1$
					List <Node> fieldNodes = SaturnW3CUtil.getChildrenByName(fieldsNode, Messages.getString("AttributeValueAssignmentDialog.Field")); //$NON-NLS-1$
					String name ;
//					List<String>dbParameter= new ArrayList<String>() ;
					
					dbDatalist.clear();
					for (Node fieldnode : fieldNodes) {
						SaturnDbDataElement  DataElement = new SaturnDbDataElement();
						name = SaturnW3CUtil.getNodeAttributeValue(fieldnode,Messages.getString("AttributeValueAssignmentDialog.Name")); //$NON-NLS-1$
						
						DataElement.setName(name);
						dbDatalist.add(DataElement);
					}
					tableViewer.setInput(dbDatalist);
//
//					if ((saturnPropertyNode.getProjectMap() != null)
//							&& saturnPropertyNode.getProjectMap().containsKey(
//									fullKeyText.getText())) {
//						dbDatalist = xmlChange((List<SaturnDbDataElement>) saturnPropertyNode
//								.getProjectMap().get(fullKeyText.getText()));
//
//					} else if (saturnPropertyNode.getWorkspaceMap() != null
//							&& saturnPropertyNode.getWorkspaceMap().containsKey(
//									fullKeyText.getText())) {
//						dbDatalist = xmlChange((List<SaturnDbDataElement>) saturnPropertyNode
//								.getWorkspaceMap().get(fullKeyText.getText()));// 得到一个list赋给第币李斯特
//					}
//					tableViewer.setInput(dbDatalist);
				}
			}
		});

		final Label descriptionLabel = new Label(container, SWT.NONE);
		final GridData gd_descriptionLabel = new GridData(SWT.LEFT, SWT.TOP,
				false, false);
		gd_descriptionLabel.verticalIndent = 10;
		descriptionLabel.setLayoutData(gd_descriptionLabel);
		descriptionLabel.setText(Messages
				.getString("AttributeValueAssignmentDialog.description")); //$NON-NLS-1$ 

		descriptionText = new Text(container, SWT.V_SCROLL | SWT.BORDER);
		descriptionText.setTextLimit(200);
		final GridData gd_descriptionText = new GridData(SWT.FILL, SWT.FILL,
				true, false, 2, 1);
		gd_descriptionText.heightHint = 50;
		gd_descriptionText.verticalIndent = 5;
		descriptionText.setLayoutData(gd_descriptionText);

		final Group group = new Group(container, SWT.NONE);
		group.setText(Messages.getString("AttributeValueAssignmentDialog.2"));  //$NON-NLS-1$
		group.setLayout(new FormLayout());
		final GridData gd_group = new GridData(SWT.FILL, SWT.FILL, true, true,
				3, 1);
		group.setLayoutData(gd_group);

		tableViewer = new TableViewer(group, SWT.MULTI | SWT.FULL_SELECTION
				| SWT.BORDER);
		table = tableViewer.getTable();
		final FormData fd_table = new FormData();
		fd_table.right = new FormAttachment(100, 0);
		fd_table.bottom = new FormAttachment(100, -10);
		fd_table.left = new FormAttachment(0, 10);
		fd_table.top = new FormAttachment(0, 10);
		table.setLayoutData(fd_table);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		tableViewer
				.setContentProvider(new SaturnSWTUtils.SaturnTableViewerDefaultContentProvider());
		tableViewer.setLabelProvider(new DBDataTableViewerLableProvider());

		/**
		 * 让表格可以直接编辑
		 */
		tableViewer.setColumnProperties(new String[] { "name", "value" }); //$NON-NLS-1$ //$NON-NLS-2$
		CellEditor[] cellEditor = new CellEditor[2];
		cellEditor[0] = null;
		cellEditor[1] = new TextCellEditor(tableViewer.getTable());
		tableViewer.setCellEditors(cellEditor);
		tableViewer.setCellModifier(new MyCellModifierLittleParameter(
				tableViewer));

		final TableColumn attrNameColumn = new TableColumn(table, SWT.NONE);
		attrNameColumn.setWidth(190);
		attrNameColumn.setText(Messages
				.getString("AttributeValueAssignmentDialog.AttributeName")); //$NON-NLS-1$

		final TableColumn attrValueColumn = new TableColumn(table, SWT.NONE);
		attrValueColumn.setWidth(190);
		attrValueColumn.setText(Messages
				.getString("AttributeValueAssignmentDialog.AttributeValue")); //$NON-NLS-1$

		// 初始化
		nameText.setText(saturnPropertyNode.getName().trim());
		nameText.setSelection(saturnPropertyNode.getName().trim().length());
		idText.setText(saturnPropertyNode.getId().trim());
		keyText.setText(saturnPropertyNode.getKey().trim());
		descriptionText.setText(saturnPropertyNode.getDescription().trim());

		// tableViewer及其相关项初始化
		initDialog();

		nameText.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				validate();
			}
		});

		fullKeyText.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				validate();
			}
		});

		return area;

	}

	private boolean validate() {

		String name = nameText.getText().trim();
		String fullyKey = fullKeyText.getText().trim();

		if (SaturnValidation.isEmpty(name)) {
			setErrorMessage(Messages.getString("AttributeValueAssignmentDialog.NameIsEmpty")); //$NON-NLS-1$
			getButton(IDialogConstants.OK_ID).setEnabled(false);
			return false;
		}

		if (SaturnValidation.isEmpty(fullyKey)) {
			setErrorMessage(Messages
					.getString("AttributeValueAssignmentDialog.FullKeyLimit")); //$NON-NLS-1$
			getButton(IDialogConstants.OK_ID).setEnabled(false);
			return false;
		}

		getButton(IDialogConstants.OK_ID).setEnabled(true);
		setErrorMessage(null);
		return true;

	}

	@Override
	protected void buttonPressed(int buttonId) {
		if (buttonId == IDialogConstants.OK_ID) {
			saturnPropertyNode.setKey(keyText.getText().trim());
			saturnPropertyNode.setDescription(descriptionText.getText().trim());
			saturnPropertyNode.setFullKey(fullKeyText.getText().trim());
			createParameters(this.dbDatalist);
			saturnPropertyNode.setName(nameText.getText().trim());
		}
		super.buttonPressed(buttonId);
	}

	protected Point getInitialSize() {
		return new Point(480, 460);
	}

	protected int getShellStyle() {
		return SWT.CLOSE | SWT.RESIZE;
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME));
	}

	private void createParameters(List<SaturnDbDataElement> dbDatalist) {
		List<SaturnParameter> parameters1 = new ArrayList<SaturnParameter>();
		SaturnParameter parameter1 = new SaturnParameter();
		parameter1.setId("1"); //$NON-NLS-1$
		parameter1.setName("saturnData"); //$NON-NLS-1$
		parameter1.setClassType("edu.ccut.saturn.component.SaturnData"); //$NON-NLS-1$
		parameter1.setPassingType("in"); //$NON-NLS-1$
		parameter1.setScope("1"); //$NON-NLS-1$
		parameter1.setDescription(""); //$NON-NLS-1$
		parameter1.setValueKey(paraValueKeyText.getText().trim());
		parameters1.add(parameter1);

		int k = 2;
		for (int i = 0; i < dbDatalist.size(); i++) {

			SaturnParameter para = new SaturnParameter();
			para.setId("" + (k)); //$NON-NLS-1$
			para.setName("key"); //$NON-NLS-1$
			para.setClassType("java.lang.String"); //$NON-NLS-1$
			para.setPassingType("in"); //$NON-NLS-1$
			para.setScope("1"); //$NON-NLS-1$
			para.setDescription(""); //$NON-NLS-1$
			para.setValueKey("'" + dbDatalist.get(i).getName().trim() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
			parameters1.add(para);
			k++;

			SaturnParameter para1 = new SaturnParameter();
			para1.setId("" + (k)); //$NON-NLS-1$
			para1.setName("filedValue"); //$NON-NLS-1$
			para1.setClassType(dbDatalist.get(i).getXmlJavaType().trim());
			para1.setPassingType("in"); //$NON-NLS-1$
			para1.setScope("1"); //$NON-NLS-1$
			para1.setDescription(""); //$NON-NLS-1$
			para1.setValueKey(dbDatalist.get(i).getNamevalue().trim());
			parameters1.add(para1);
			k++;
		}
		saturnPropertyNode.setParameters(parameters1);
	}

	@SuppressWarnings("unchecked") //$NON-NLS-1$
	private void initDialog() {
		List<SaturnDbDataElement> dbDatalist = new ArrayList<SaturnDbDataElement>();
		SaturnDbDataElement saturn = null;
		int k = 0;

		if (saturnPropertyNode.getParameters().size() == 0) {
			this.dbDatalist = dbDatalist;
			return;
		}

		for (int i = 1; i < saturnPropertyNode.getParameters().size(); i++) {
			if (i % 2 != 0) {
				saturn = new SaturnDbDataElement();
				saturn.setName(ConversionUtil.quotationRemove(saturnPropertyNode
						.getParameters().get(i).getValueKey().trim()));
				k++;
			} else {
				saturn.setNamevalue(saturnPropertyNode.getParameters().get(i)
						.getValueKey().trim());
				saturn.setXmlJavaType(saturnPropertyNode.getParameters().get(i)
						.getClassType().trim());
				k++;
			}
			if (k == 2) {
				dbDatalist.add(saturn);
				k = 0;
			}
		}
		paraValueKeyText.setText(saturnPropertyNode.getParameters().get(0)
				.getValueKey());
		fullKeyText.setText(saturnPropertyNode.getFullKey());
		this.dbDatalist = dbDatalist;
		tableViewer.setInput(dbDatalist);
	}

	private List<SaturnDbDataElement> xmlChange(List<SaturnDbDataElement> list) {
		for (SaturnDbDataElement saturn : list) {
			for (SaturnDbDataElement saturn1 : dbDatalist) {
				if (saturn.getName().equals(saturn1.getName())) {
					saturn.setNamevalue(saturn1.getNamevalue());
				}
			}
		}
		return list;// 
	}

	/**
	 * 判断对话框OK确认键是否可用，如果FullKey为空，不可用；反之，可用
	 * 
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		super.createButtonsForButtonBar(parent);
		if (("".equals(fullKeyText.getText().trim()) || ("".equals(nameText //$NON-NLS-1$ //$NON-NLS-2$
				.getText().trim())))) {
			getButton(IDialogConstants.OK_ID).setEnabled(false);
		} else {
			getButton(IDialogConstants.OK_ID).setEnabled(true);
		}
	}
}
